<template>
  <view class="main">
    <div class="details">
      <Editor  class="h100" 
        :value="content"
        :plugins="plugins"
        @change="handleChange"
        :locale="zhHans"
        :upload-images="handleUploadImages"
      />
    </div>
    <el-button type="primary" @click="handleSubmit">发送博文</el-button>
  </view>
</template>

<script setup lang="ts">
import { Editor } from '@bytemd/vue-next'
//   import 'juejin-markdown-themes/dist/juejin.min.css'
import 'bytemd/dist/index.css'
import gfm from '@bytemd/plugin-gfm'
import highlight from '@bytemd/plugin-highlight'
import zhHans from 'bytemd/locales/zh_Hans.json'
import gemoji from '@bytemd/plugin-gemoji'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import { request } from '../utils/request'
import{ref} from 'vue'
import type { ResponseType } from 'axios'
import { ElMessage } from 'element-plus'

let content = ref('')
const handleChange = (v: string) => {
  content.value = v
}
//添加的插件
const plugins = [
  gfm(),
  highlight(),
  gemoji(),
  mediumZoom()
]


//上传图片
const handleUploadImages = async(files: File[]) => {
  debugger
  let imgs: any= []
  const item = files[0]
  let formData = new FormData();
  formData.append('file', item)
  await uploadFile(formData).then(url => {
    imgs.push({url})
  })
  return imgs
}

function uploadFile(formData: FormData) {
  return new Promise((resolve, reject) => {
     request({
      url: "/api/blog/upload",
      method: "post",
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(r => {
      resolve(import.meta.env.VITE_GLOBL_MINIO_PATH + r.fileName)
    }).catch(e => {
      reject(e)
    })
  });

}

const handleSubmit = (e:Event) => {
  request({
    url: '/api/blog/addBlog',
    method: 'post',
    data: {'blogContent': content.value}
  }).then((r) => {
    ElMessage.success(r.msg)
  })
}
</script>


<style scoped>
.h100 /deep/ .bytemd {
    height: 100vh !important;
}

#app {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  font-weight: normal;
}
</style>